package com.faxsun.web.controller.user;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.faxsun.web.security.authentication.ThirdPartyLoginServer;

import mblog.web.controller.BaseController;

@Controller
@RequestMapping("/uc")
public class WeChatController extends BaseController {
	@Autowired
	ThirdPartyLoginServer login3rdService;

	/***
	 * Handle 3rd party login button request from Web Page. Used to create
	 * "code".
	 ***/
	@RequestMapping(value = "/thirdRequest", method = RequestMethod.GET)
	public void thirdPartyRequest(HttpServletRequest request, HttpServletResponse response) {
		// 记录refer，即验证成功跳转回来的url
		request.getSession().setAttribute(HttpHeaders.REFERER, request.getHeader(HttpHeaders.REFERER));
		login3rdService.requestURL(request, response);
	}

	/*** Handle 3rd party login request ***/
	@RequestMapping(value = "/thirdparty/{channelId}", method = RequestMethod.GET)
	public String thirdPartyLogin(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("channelId") String channelId) {
		String path = null;
		login3rdService.handle(request, response, path, channelId);
		String referer = (String) request.getSession().getAttribute(HttpHeaders.REFERER);
		if (StringUtils.isEmpty(referer)) {
			return "redirect:/";
		}
		request.getSession().removeAttribute(HttpHeaders.REFERER);
		return "redirect:"+referer;
	}
}
